﻿using System;
using Microsoft.Xna.Framework;
using WindowsGame.Components;
using WindowsGame.Enums;

namespace WindowsGame.GameObjects
{
	public class Weapon : GameObject
	{
		private Vector3 bulletOffset;
		private Boolean active;
		private Double endTime;
		private const float shotSpeed = 150.0f;

		public void LoadContent(Vector3 bulletOffset)
		{
			base.LoadContent();

			this.active = false;
			this.bulletOffset = bulletOffset;
		}

		public void Update(TimeSpan time, TimeSpan elapsedTime, Boolean fire, Spaceship ship)
		{
			if (fire)
			{
				Start(time, ship);
				return;
			}
			if (!active)
			{
				return;
			}

			if (time.TotalSeconds > endTime)
			{
				active = false;
			}

			var physicsComponent = GetComponent<PhysicsComponent>();
			physicsComponent.UpdatePosition(elapsedTime, Vector3.Zero);
			physicsComponent.Update();
		}

		public void Draw()
		{
			if (!active)
			{
				return;
			}

			var modelComponent = GetComponent<ModelComponent>();
			var physicsComponent = GetComponent<PhysicsComponent>();

			modelComponent.Draw(physicsComponent.WorldMatrix);
		}

		private void Start(TimeSpan time, Spaceship ship)
		{
			active = true;

			var weaponComponent = GetComponent<WeaponComponent>();
			Double lifetime = weaponComponent.Lifetime;
			endTime = time.TotalSeconds + lifetime;

			var shipPhysicsComponent = ship.GetComponent<PhysicsComponent>();
			var physicsComponent = GetComponent<PhysicsComponent>();

			// Set position.
			Vector3 position = Vector3.Transform(bulletOffset, shipPhysicsComponent.WorldMatrix);
			physicsComponent.Position = position;

			// Set rotation.
			Single angle = shipPhysicsComponent.Rotation.Z;
			physicsComponent.Rotation = new Vector3(physicsComponent.Rotation.X, physicsComponent.Rotation.Y, angle);

			// Set direction.
			Single x = (Single)(-Math.Sin(angle));
			Single y = (Single)(Math.Cos(angle));
			Vector3 direction = new Vector3(x, y, 0);

			// Set velocity.
			Vector3 velocity = Vector3.Multiply(direction, shotSpeed);
			velocity += shipPhysicsComponent.Velocity;

			physicsComponent.UpdateVelocity(velocity);
			physicsComponent.Update();
		}
	}
}